<?php
// $Id$

/**
 * Controller_NewsNotice 控制器
 */
class Controller_NewsNotice extends Controller_Prepare
{
    /**
     * 新闻显示专用页面
     */
    public function actionIndex()
    {
        // Error handling 初步过滤获得的值，必须满足值类型
        $Gnews_id    = isset($_GET['news_id'])  && is_numeric($_GET['news_id'])  ? $_GET['news_id']    : NULL;
        $Gctgry_id   = isset($_GET['ctgry_id']) && is_numeric($_GET['ctgry_id']) ? $_GET['ctgry_id']   : NULL;
        $Gsubaction  = isset($_GET['subaction'])                                 ? $_GET['subaction']  : NULL;
        $Gtag        = isset($_GET['tag'])                                       ? $_GET['tag']        : NULL;
        $Gpage       = isset($_GET['page'])     && is_numeric($_GET['page'])     ? $_GET['page']       : 0;
        // 搜索新闻,  新闻查询条件
        $Gqtitlebody = isset($_GET['qtitlebody'])                                ? $_GET['qtitlebody'] : NULL;

        /**
         * 由于多次使用，定义 $sort
         *
         * @var string
         */
        $sort = Q::ini('appini/sort');

        /**
         * 准备 1. 获得各子分类 key-menu
         *
         * @var array $nc, $ntc, $ec, $sc
         * @var array $allc
         */
        $allc = NewsCategory::getSelfArrayId(array(4,7,8,23));

        /**
         * 步骤 1. 获取当前显示的新闻
         *
         * @var object $currentNews
         */
        if(isset($Gnews_id))
        {
            $currentNews = News::find('news_id = ?', $Gnews_id)->query();
        }
        elseif(isset($Gctgry_id) && in_array($Gctgry_id, $allc))
        {
            $currentNews = News::find(NewsCategory::genCondition($Gctgry_id))->order($sort)->query();
        }
        elseif(CIB::_SQL_filter($Gtag))
        {
            $currentNews = News::find('category_id in (?) AND tag like ?', $allc, "%,{$Gtag},%")->order($sort)->query();
        }
        elseif(CIB::_SQL_filter($Gqtitlebody))
        {
            $currentNews = News::find('title like ? AND category_id in (?)', '%'.$Gqtitlebody.'%', $allc)
                ->orWhere('body like ? AND category_id in (?)', '%'.$Gqtitlebody.'%', $allc)
                ->order($sort)->query();
        }
        else
        {
            $currentNews = News::find('category_id in (?)', $allc)->order($sort)->query();
        }

        /**
         * Error handling 如果恶意输入不存在的 ctgry_id 或 news_id，导致当前新闻不存在，则显示最新一条新闻
         * Error handling 检查 news_id
         * 找不到新闻时，返回对象QColl 的 _props 属性所有字段均有值但是值为''，此时用 empty 无效，必须以属性来判断
         */
        if($currentNews->title == '')
        {
            $currentNews = News::find('category_id in (?)', $allc)->order($sort)->query();
        }

        /**
         * 处理一下 $Gctgry_id
         */
        if(in_array($Gctgry_id, $allc) === FALSE)
        {
            $Gctgry_id = $currentNews->category_id;
        }

        /**
         * 更新当前新闻"阅读"值 hasread = hasread + 1
         */
        News::meta()->updateDbWhere(new QDB_Expr('hasread = hasread + 1'), 'news_id = ?', $currentNews->news_id);

        /**
         * 步骤 2. 获取同标签新闻
         * PS： 最好也做成对象形式，而非数组形式
         * 数据表中的标签形式如 ,美国与英国,  左右都有','
         *
         * @var array $relavantNews, $tags
         */
        $relaventNews = NULL;
        $tags = NULL;
        if($currentNews->tag)
        {
            $currentNews->tag = trim($currentNews->tag, ','); // 删除左右逗号

            if($currentNews->tag != '')
            {
                $tags = explode(',', $currentNews->tag);
                $relaventNews = array();
                foreach($tags as $tag)
                {
                    $relaventNews[$tag] = News::find('tag like ?', "%,{$tag},%")
                        ->where('news_id != ?', $currentNews->news_id)
                        ->where('category_id in (?)', $allc)
                        ->all()->order($sort)->query();
                }
            }
        }

        /**
         * 步骤 3. 显示右侧面板
         *
         * {return} $_SESSION
         */
        if(!isset($_SESSION['news_cur_page']))     {$_SESSION['news_cur_page']     = 1;}
        if(!isset($_SESSION['notice_cur_page']))   {$_SESSION['notice_cur_page']   = 1;}
        if(!isset($_SESSION['exchange_cur_page'])) {$_SESSION['exchange_cur_page'] = 1;}
        if(!isset($_SESSION['students_cur_page'])) {$_SESSION['students_cur_page'] = 1;}

        if(!isset($_SESSION['news_cur_ctgry']))     $_SESSION['news_cur_ctgry']     = 4;
        if(!isset($_SESSION['notice_cur_ctgry']))   $_SESSION['notice_cur_ctgry']   = 23;
        if(!isset($_SESSION['exchange_cur_ctgry'])) $_SESSION['exchange_cur_ctgry'] = 8;
        if(!isset($_SESSION['students_cur_ctgry'])) $_SESSION['students_cur_ctgry'] = 7;

        if($Gctgry_id && $Gnews_id)
        {
            // Error handling 此行必须，否则点击news 会刷新面板，显示该分类新闻，造成错误
        }
        else
        {
            if($Gsubaction)
            {
                // Error handling 检查 subaction，只能改一个 $_SESSION['*_cur_ctgry'] 的值
                switch($Gsubaction)
                {
                    case 'news':
                        $_SESSION['news_cur_page']          = $Gpage;
                        if(in_array($Gctgry_id, NewsCategory::getSelfArrayId(4)))
                        {
                            $_SESSION['news_cur_ctgry']     = $Gctgry_id;
                        }
                        break;
                    case 'notice':
                        $_SESSION['notice_cur_page']        = $Gpage;
                        if(in_array($Gctgry_id, NewsCategory::getSelfArrayId(23)))
                        {
                            $_SESSION['notice_cur_ctgry']   = $Gctgry_id;
                        }
                        break;
                    case 'exchange':
                        $_SESSION['exchange_cur_page']      = $Gpage;
                        if(in_array($Gctgry_id, NewsCategory::getSelfArrayId(8)))
                        {
                            $_SESSION['exchange_cur_ctgry'] = $Gctgry_id;
                        }
                        break;
                    case 'students':
                        $_SESSION['students_cur_page']      = $Gpage;
                        if(in_array($Gctgry_id, NewsCategory::getSelfArrayId(7)))
                        {
                            $_SESSION['students_cur_ctgry'] = $Gctgry_id;
                        }
                        break;
                    default :
                        break;
                }
            }
        }

        /**
         * 注意查询条件
         * 分页数据
         *
         * @var array $news, $notice, $exchange, $students
         */
        $news = News::find(NewsCategory::genCondition($_SESSION['news_cur_ctgry']))->all()->order($sort)
            ->limitPage($_SESSION['news_cur_page'], Q::ini('appini/news_per_page'))->fetchPagination($newspg)->get(); // $pagination

        $notice = News::find(NewsCategory::genCondition($_SESSION['notice_cur_ctgry']))->all()->order($sort)
            ->limitPage($_SESSION['notice_cur_page'], Q::ini('appini/notice_per_page'))->fetchPagination($noticepg)->get(); // $pagination

        $exchange = News::find(NewsCategory::genCondition($_SESSION['exchange_cur_ctgry']))->all()->order($sort)
            ->limitPage($_SESSION['exchange_cur_page'], Q::ini('appini/exchange_per_page'))->fetchPagination($exchangepg)->get(); // $pagination

        $students = News::find(NewsCategory::genCondition($_SESSION['students_cur_ctgry']))->all()->order($sort)
            ->limitPage($_SESSION['students_cur_page'], Q::ini('appini/students_per_page'))->fetchPagination($studentspg)->get(); // $pagination

        /**
         * 步骤 5.1 处理一般模糊查询搜索结果：$qtitlebody
         *
         * @var array $qtitlebodyRecords
         */
        $qtitlebodyRecords = array();
        if(CIB::_SQL_filter($Gqtitlebody))
        {
            $qtitlebodyRecords = News::find('title like ? AND category_id in (?)', '%'.$Gqtitlebody.'%', $allc)
                ->orWhere('body like ? AND category_id in (?)', '%'.$Gqtitlebody.'%', $allc)
                ->all()->order($sort)->query();
        }

        /**
         * 步骤 5.2 处理标签搜索结果：$tag
         *
         * @var array $tagRecords
         */
        $tagRecords = array();
        if(CIB::_SQL_filter($Gtag))
        {
            $tagRecords = News::find('tag like ? AND category_id in (?)', '%,'.$Gtag.',%', $allc)
                ->where('category_id in (?)', $allc)
                ->all()->order($sort)->query();
            
            // 更新 hit_as_query 字段
            $t = Tag::find('category = ? AND tag = ?', '新闻通知', $Gtag)->query();
            if($t->tag != '')
            {
                $t->hit_as_query += 1;
                $t->save();
            }
        }

        /**
         * CSS HIGHTLIGHT
         *
         * @var string $css
         *
         * works under _rewrite_ mode ONLY!
         * currently   _router_
         */
        $css = "a[href*='_c{$Gctgry_id}.html']:link, a[href*='_c{$Gctgry_id}.html']:visited".HIGHLIGHT_CSS_TABS;
        $css .= "a[href*='_{$currentNews->news_id}.html']".HIGHLIGHT_CSS;

        $this->_view['currentNews']  = $currentNews;
        $this->_view['tags']         = $tags;             // 当前新闻标签
        $this->_view['relaventNews'] = $relaventNews;

        $this->_view['qtitlebodyRecords'] = $qtitlebodyRecords;
        $this->_view['tagRecords']        = $tagRecords;

        $this->_view['news']     = $news;
        $this->_view['notice']   = $notice;
        $this->_view['exchange'] = $exchange;
        $this->_view['students'] = $students;

        $this->_view['newspg']     = $newspg;
        $this->_view['noticepg']   = $noticepg;
        $this->_view['exchangepg'] = $exchangepg;
        $this->_view['studentspg'] = $studentspg;

        $this->_view['css'] = $css;
    }
}